import Toast from "../Base/Toast";
import { resMgr } from "./ResMgr";

class ToastMgr {
    public static instance: ToastMgr = null
    public static getInstance() {
        if (!ToastMgr.instance) {
            ToastMgr.instance = new ToastMgr()
        }
        return ToastMgr.instance
    }

    private _rootNode: cc.Node = null
    private _toastCache: Toast[] = []
    private _currQueue: Toast[] = []


    public initRoot(root: cc.Node) {
        this._rootNode = root.getChildByName("toastRoot")
    }

    public dispose() {
        this._currQueue.forEach((v) => {
            v.pushToCache()
        })
        this._rootNode = null
    }

    public showToast(str: string) {
        if (!this._rootNode) return
        if (this._toastCache.length <= 0) {
            resMgr.load("Prefab/Common/Toast", cc.Prefab).then((res: cc.Prefab) => {
                if (res && this._rootNode) {
                    let node = cc.instantiate(res)
                    let view = node.getComponent("Toast")
                    this.pushToCache(view)
                    this.showToast(str)
                }
            })
        } else {
            this._currQueue.forEach((v) => {
                v.move()
            })
            let view = this._toastCache.shift()
            this._rootNode.addChild(view.node)
            view.setParam(str)
            view.setComplateCallBack(this.pushToCache.bind(this))
            this._currQueue.push(view)
        }
    }

    public pushToCache(view: Toast) {
        let index = this._currQueue.indexOf(view)
        if (index >= 0) {
            this._currQueue.splice(index, 1)
        }
        view.node.parent = null
        this._toastCache.push(view)
    }

}

export let toastMgr = ToastMgr.getInstance()
